<?php

class User {

    /**
     * 判断用户是否已经存在
     * @param string $username 用户名
     */
    public static function isHave($username) {
        global $_SGLOBAL;
        return $_SGLOBAL['db']->getCount('member', array('username' => $username));
    }

    /**
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email email
     * @param int $gid 用户组id
     * @param int $cid 所属公司id
     * @param string $nickname 昵称
     * @param int $cadmin 是否是该公司的管理员
     */
    public static function addUser($username, $password, $email, $gid, $cid, $nickname='', $cadmin=0) {
        global $_SGLOBAL;
        $setarr = array('username' => $username,
            'password' => md5($password),
            'gid' => $gid,
            'dateline' => $_SGLOBAL['timestamp'],
            'lastupdate' => $_SGLOBAL['timestamp'],
        );
        $uid = $_SGLOBAL['db']->insertTable('member', $setarr);
        if ($uid) {
            $setarr = array('uid' => $uid,
                'cid' => $cid,
                'cadmin' => $cadmin,
                'nickname' => $nickname,
                'email' => $email);
            $_SGLOBAL['db']->insertTable('memberfields', $setarr);

            //更新公司的用户数
            if ($cid) {
                $_SGLOBAL['db']->query("UPDATE " . Utils::tname('company') . " SET membernum=membernum+1 WHERE cid=$cid");
            }
        }
        return $uid;
    }

    /**
     * 取得用户对象
     * @param int $uid
     */
    public static function getUser($uid) {
        global $_SGLOBAL;
        $sql = 'SELECT m.*,mf.email,mf.nickname,mf.cid,mf.cadmin FROM';
        $sql.=' ' . Utils::tname('member') . ' m' . ' LEFT JOIN ' . Utils::tname('memberfields') . ' mf';
        $sql.=' ON m.uid=mf.uid';
        return $_SGLOBAL['db']->fetchArray($_SGLOBAL['db']->query($sql));
    }

}

?>
